// pages/own/own.js
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    isLogin:false
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },



  //-------------------------授权登录----------------------
  getUserInfo(data) {
    //判断用户已经授权
    if (!app.globalData.hasLogin) {
      //获取用户凭证
      var that = this;
      wx.login({
        success: (res) => {
          // console.log(res);
          if (res.code) {
            wx.request({
              url: app.globalData.myUrl + '/login',
              method:"POST",
              header: {"Content-Type":"application/x-www-form-urlencoded"},
              data: {
                code: res.code
              },
              success: function (res) {
                console.log(res);
                if(res.data.token == null ||res.data.token == ""){
                  that.errShowToast('发生未知错误');
                  return;
                }
                app.globalData.hasLogin = true;
                app.globalData.token = res.data.token;
                that.sucShowToast('登陆成功');
                that.time();
                wx.request({
                  url: app.globalData.myUrl + '/getUserInfo',
                  method:"GET",
                  data: {
                    token: app.globalData.token
                  },
                  success: function (res) {
                    // console.log(res.data);
                    if (res.data.success) {
                      that.setData({
                        user: res.data.msg,
                        isLogin: true
                      })
                    } else {
                      that.errShowToast(res.data.msg);
                    }
                  },
                })
              }
            })
          }
        },
        fail: (res) => {},
      })
    } else {
      this.sucShowToast('已登录')
    }
  },
  getUserProfile(e) {
    var that = this;
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log(res);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        wx.request({
          url: app.globalData.myUrl + '/register',
          method:"POST",
          header: {"Content-Type":"application/x-www-form-urlencoded"},
          data: {
            token: app.globalData.token,
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            gender: res.userInfo.gender,
            province: res.userInfo.province,
          },
          success: function (res) {
            // console.log(res.data);
            if (res.data.success) {
              that.setData({
                user: res.data.msg
              })
            } else {
              that.errShowToast(res.data.msg);
            }
          },
        })
      }
    })
  },


  //-------------------------退出登录----------------------
  logout() {
    var that = this;
    if (!app.globalData.hasLogin) {
      this.errShowToast('你还没有登录哦');
      return
    }
    wx.request({
      url: app.globalData.myUrl + '/logout',
      method:"POST",
      header: {"Content-Type":"application/x-www-form-urlencoded"},
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        var msg = res.data.msg;
        if (msg) {
          var toastText = msg;
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
          app.globalData.hasLogin = false;
          app.globalData.uuid = null;
          that.setData({
            user: null,
            isLogin: false
          })
        }
      }
    })
  },

  //-------------------------获取用户文章----------------------------
  myArticle() {
    if (!app.globalData.hasLogin) {
      this.errShowToast('你还没有登录哦');
      return
    }
    wx.navigateTo({
      url: '/pages/ownData/ownData'
    })
  },

  //-------------------------获取用户树洞----------------------------
  myTree() {
    if (!app.globalData.hasLogin) {
      this.errShowToast('你还没有登录哦');
      return
    }
    wx.navigateTo({
      url: '/pages/ownTreeData/ownTreeData'
    })
  },
  //---------------------------函数封装------------------------------
  errShowToast: function (toastText) {
    wx.showToast({
      title: toastText,
      image: '/images/password.png',
      duration: 2000
    });
  },
  sucShowToast: function (toastText) {
    wx.showToast({
      title: toastText,
      duration: 2000
    });
  },

  //----------------------更新用户文章数量-----------------------
  getArticleNum: function () {
    var that = this;
    if (!app.globalData.hasLogin) {
      this.errShowToast('你还没有登录哦');
      return
    }
    wx.request({
      url: app.globalData.myUrl + '/user/articlesNum',
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.success) {
          that.data.user.articleNum = res.data.msg;
          that.setData({
            user: that.data.user
          })
        }
      }
    })
  },

  //----------------------更新用户文章数量-----------------------
  getTreeHoleNum: function () {
    var that = this;
    if (!app.globalData.hasLogin) {
      this.errShowToast('你还没有登录哦');
      return
    }
    wx.request({
      url: app.globalData.myUrl + '/user/treeHoleNum',
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.success) {
          that.data.user.treeHoleNum = res.data.msg;
          that.setData({
            user: that.data.user
          })
        }
      }
    })
  },
  //----------------------更新用户未读评论数量-----------------------
  getNewCommentNum: function () {
    var that = this;
    if (!app.globalData.hasLogin) {
      this.errShowToast('你还没有登录哦');
      return
    }
    wx.request({
      url: app.globalData.myUrl + '/user/newCommentNum',
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.success) {
          that.data.user.unreadComment = res.data.msg;
          that.setData({
            user: that.data.user
          })
        }
      }
    })
  },
  //----------------------更新用户未读意见数量-----------------------
  getNewOpinionNum: function () {
    var that = this;
    if (!app.globalData.hasLogin) {
      this.errShowToast('你还没有登录哦');
      return
    }
    wx.request({
      url: app.globalData.myUrl + '/user/newOpinionNum',
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.success) {
          that.data.user.unreadOpinion = res.data.msg;
          that.setData({
            user: that.data.user
          })
        }
      }
    })
  },

  //-------------------------------跳转------------------------------------------
  newInformation() {
    var that = this;
    if (!app.globalData.hasLogin) {
      that.errShowToast('你还没有登录喔');
      return;
    }
    wx.navigateTo({
      url: '/pages/newInformation/newInformation'
    })
  },
  newInformationtwo() {
    var that = this;
    if (!app.globalData.hasLogin) {
      that.errShowToast('你还没有登录喔');
      return;
    }
    wx.navigateTo({
      url: '/pages/newInformationtwo/newInformationtwo'
    })
  },
  // 账号设置
  newInformationthree(e) {
    var that = this;
    if (!app.globalData.hasLogin) {
      that.errShowToast('你还没有登录喔');
      return;
    }
    // console.log(e.currentTarget.dataset.titleimg);
    wx.navigateTo({
      url: '/pages/newInformationthree/newInformationthree?titleImg='+e.currentTarget.dataset.titleimg
    })
  },

  //------------------------定时器(为了减轻服务器负担,只在演示时开)----------------------------
  time: function () {
    var that = this;
    if (app.globalData.openTime) {
      setInterval(function () {
        if (app.globalData.hasLogin) {
          that.getArticleNum();
          that.getTreeHoleNum();
          that.getNewCommentNum();
          that.getNewOpinionNum();
        }
      }, 3000);
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.hasLogin && !app.globalData.openTime) {
      this.getArticleNum();
      this.getTreeHoleNum();
      this.getNewCommentNum();
      this.getNewOpinionNum();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (app.globalData.hasLogin && !app.globalData.openTime) {
      this.getArticleNum();
      this.getTreeHoleNum();
      this.getNewCommentNum();
      this.getNewOpinionNum();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 分享到朋友圈
   */
  // onShareTimeline: function() {
  //   return {
  //     title: '一个小demo',
  //     imageUrl: "https://www.kongbai121.xyz/drawing-bed/2023-01/59e40761-c197-4b17-be36-bfbd1f2cfa1c.jpg"
  //   }
  // },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '一个小demo',
      path: '/pages/loading/loading',
      imageUrl: "https://www.kongbai121.xyz/drawing-bed/2023-01/59e40761-c197-4b17-be36-bfbd1f2cfa1c.jpg"
    }
  }
})